<template>
  <h-drawer
    :model-value="visible"
    :title="isAdd ? '新增网点工程师' : '详细信息(可编辑)'"
    :loading="
      onsaveloading ||
      getNetworkDetailEmpListDetailLoading ||
      saveLoading ||
      judgeEmpIsJoinNetworkLoading
    "
    :width="700"
    unit="px"
    :h-drawer-padding-top="30"
    @close="onCancel"
  >
    <el-form
      ref="formRef"
      :model="networkEmpVo"
      :rules="rulesForm"
      label-position="top"
      class="body"
      inline-message
    >
      <div class="customer_service_form">
        <!-- 手机号码 -->
        <el-form-item
          :rules="[
            { validator: phone(networkEmpVo.accountUserPhone), trigger: ['blur', 'change'] },
          ]"
          label="手机号码（账号）"
          prop="accountUserPhone"
          class="phone_form_item"
        >
          <div class="find_user_container">
            <el-input
              v-model.trim="networkEmpVo.accountUserPhone"
              clearable
              maxlength="11"
              placeholder="请输入手机号码"
              @keyup="
                networkEmpVo.accountUserPhone = networkEmpVo.accountUserPhone.replace(/[^\d]/g, '')
              "
            />
            <h-plain-button
              :loading="getAccountInfoLoading"
              @click="findBtn(networkEmpVo.accountUserPhone)"
            >
              查询
            </h-plain-button>
          </div>
        </el-form-item>

        <!-- 工程师等级 -->
        <el-form-item label="工程师等级" class="level_form_item">
          <el-select
            v-model="networkEmpVo.networkEmpLevelId"
            :remote-method="getNetworkEmpPageSelectList"
            class="select_item"
            clearable
            filterable
            placeholder="工程师等级"
            remote
            remote-show-suffix
          >
            <el-option
              v-for="(item, index) in networkEmpLevelList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 姓名 -->
        <el-form-item label="姓名" prop="accountUserName" class="name_form_item">
          <el-input
            v-model.trim="networkEmpVo.accountUserName"
            clearable
            placeholder="请输入姓名"
            maxlength="100"
          />
        </el-form-item>

        <!-- 人员编号 -->
        <el-form-item label="人员编号" prop="number" class="name_form_item">
          <el-input
            v-model.trim="networkEmpVo.number"
            clearable
            placeholder="请输人员编号"
            maxlength="100"
          />
        </el-form-item>

        <!-- 工程师技能 -->
        <el-form-item label="工程师技能" class="skill_form_item">
          <el-select
            v-model="networkEmpVo.networkEmpSkillIds"
            :remote-method="getNetworkSkillPageSelectList"
            clearable
            filterable
            multiple
            placeholder="工程师技能"
            remote
            remote-show-suffix
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            class="select_item"
          >
            <el-option
              v-for="(item, index) in networkEmpSkillList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <div class="radio_container">
          <!-- 人员状态 -->
          <el-form-item label="人员状态" class="form_item">
            <el-radio-group v-model="networkEmpVo.quit">
              <el-radio :value="false" size="small">启用</el-radio>
              <el-radio :value="true" size="small">禁用</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 角色管理 -->
          <el-form-item v-if="props.networkId" label="角色管理" class="form_item">
            <el-radio-group v-model="networkEmpVo.superManager">
              <el-radio :value="false" size="small">工程师</el-radio>
              <el-radio :value="true" size="small">管理员</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 结单策略 -->
          <el-form-item label="接单策略" class="form_item">
            <el-radio-group v-if="teamType == 2" :disabled="teamType == 2" :model-value="true">
              <el-radio :value="false" size="small">手动确认</el-radio>
              <el-radio :value="true" size="small">自动确认</el-radio>
            </el-radio-group>
            <el-radio-group
              v-else
              v-model="networkEmpVo.autoSureReceiveOrder"
              :disabled="teamType == 2"
            >
              <el-radio :value="false" size="small">手动确认</el-radio>
              <el-radio :value="true" size="small">自动确认</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- <el-form-item label="个人仓库" class="form_item">
            <el-radio-group v-model="networkEmpVo.enableStore">
              <el-radio :value="true" size="small">启用</el-radio>
              <el-radio :value="false" size="small">禁用</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </div>
      </div>
      <div v-if="networkEmpVo.fieldVals.length > 0" class="custom_field">
        <el-form-item
          v-for="(field, fieldIndex) in customFieldRender.txtSelect"
          :key="fieldIndex"
          :label="field.name"
          :prop="field.formItemProp"
          :rules="field.rules"
          class="text_select"
        >
          <el-input
            v-if="field.type === 1"
            v-model.trim="networkEmpVo.fieldVals[field.sourceArrIndex].value"
            :placeholder="field.tip"
            clearable
            type="text"
            maxlength="100"
          />
          <el-select
            v-if="field.type === 3"
            v-model="networkEmpVo.fieldVals[field.sourceArrIndex].value"
            :placeholder="field.tip"
            clearable
          >
            <el-option
              v-for="option in field.contents"
              :key="option.id"
              :label="option.val"
              :value="option.val"
            />
          </el-select>
          <el-select
            v-if="field.type === 4"
            v-model="networkEmpVo.fieldVals[field.sourceArrIndex].value"
            :placeholder="field.tip"
            clearable
            collapse-tags
            collapse-tags-tooltip
            multiple
          >
            <el-option
              v-for="option in field.contents"
              :key="option.id"
              :label="option.val"
              :value="option.val"
            />
          </el-select>
        </el-form-item>
        <div class="radio_check_box_rate">
          <el-form-item
            v-for="(field, fieldIndex) in customFieldRender.radioCheckboxRate"
            :key="fieldIndex"
            :label="field.name"
            :prop="field.formItemProp"
            :rules="field.rules"
          >
            <el-radio-group
              v-if="field.type === 3"
              v-model="networkEmpVo.fieldVals[field.sourceArrIndex].value"
            >
              <el-radio
                v-for="(option, optionIndex) in field.contents"
                :key="optionIndex"
                :value="option.val"
                size="small"
                >{{ option.val }}</el-radio
              >
            </el-radio-group>
            <el-checkbox-group
              v-if="field.type === 4"
              v-model="networkEmpVo.fieldVals[field.sourceArrIndex].value"
            >
              <el-checkbox
                v-for="option in field.contents"
                :key="option.id"
                :value="option.val"
                size="small"
              >
                {{ option.val }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        <el-form-item
          v-for="(field, fieldIndex) in customFieldRender.uploadFile"
          :key="fieldIndex"
          :label="field.name"
          :prop="field.formItemProp"
          :rules="field.rules"
          class="upload_file"
        >
          <el-upload
            v-model="networkEmpVo.fieldVals[field.sourceArrIndex].imgarr"
            :accept="field.type == 5 ? 'image/*' : field.type == 6 ? '.pdf' : 'video/*'"
            :auto-upload="false"
            :on-change="
              (file) => {
                handleChange2(file, field)
              }
            "
            :show-file-list="false"
            action="#"
            drag
            multiple
          >
            <el-icon color="#606266" size="32">
              <upload-filled />
            </el-icon>
            <div style="line-height: 16px; color: #606266">
              点击上传{{ field.type === 5 ? '图片' : field.type === 6 ? 'pdf格式文件' : '视频' }}
            </div>
          </el-upload>
          <ul class="file_list">
            <li
              v-for="(it, index) in networkEmpVo.fieldVals[field.sourceArrIndex].imgarr"
              :key="index"
              class="file_item"
            >
              <h-image
                v-if="
                  it.name
                    ? it.name.replace(/.+\./, '') == 'pdf'
                    : it.image.replace(/.+\./, '') == 'pdf'
                "
                :src="pdf"
                :width="70"
                :height="43.75"
                :mask-btn-gap="3"
                fit="contain"
                @del="deleteItem2(field.sourceArrIndex, index)"
                @preview="lookFile(it.image, 'pdf')"
              />
              <h-image
                v-else-if="
                  right_type.includes(
                    it.name ? it.name.replace(/.+\./, '') : it.image.replace(/.+\./, ''),
                  )
                "
                :src="video"
                :width="70"
                :height="43.75"
                :mask-btn-gap="3"
                fit="contain"
                @del="deleteItem2(field.sourceArrIndex, index)"
                @preview="lookFile(it.image, 'film')"
              >
                <Film />
              </h-image>
              <h-image
                v-else
                :preview-src-list="
                  networkEmpVo.fieldVals[field.sourceArrIndex].imgarr.map((item) => item.image)
                "
                :src="it.image"
                :initial-index="index"
                fit="contain"
                :width="70"
                :height="43.75"
                :padding="2"
                :mask-btn-gap="3"
                @del="deleteItem2(field.sourceArrIndex, index)"
              />
              <el-tooltip effect="dark" placement="top">
                <template #content>
                  {{
                    it.name
                      ? it.name
                      : it.image?.substring(
                          it.image.lastIndexOf('/') + 1,
                          it.image.lastIndexOf('_'),
                        ) + it.image?.substring(it.image.lastIndexOf('.'))
                  }}
                </template>
                <div class="file_name">{{
                  it.name
                    ? it.name
                    : it.image?.substring(
                        it.image.lastIndexOf('/') + 1,
                        it.image.lastIndexOf('_'),
                      ) + it.image?.substring(it.image.lastIndexOf('.'))
                }}</div>
              </el-tooltip>
            </li>
          </ul>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <HButton is-modal type="primary" @click="onSave">保存</HButton>
      <HButton is-modal @click="onCancel">取消</HButton>
    </template>
  </h-drawer>

  <!-- 文件查看 -->
  <el-dialog
    v-model="dialogContract"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :draggable="true"
    :title="isPdf == 'pdf' ? '查看附件' : '查看视频'"
  >
    <iframe
      v-if="isPdf == 'pdf'"
      :src="`${file}`"
      frameborder="0"
      height="700"
      width="100%"
    ></iframe>
    <video v-else :src="`${file}`" autoplay controls style="width: 100%"></video>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { PropType, ref, toRefs, watch } from 'vue'
  import type { UploadFile } from 'element-plus'
  import { ElMessage, ElDialog, ElUpload, ElIcon } from 'element-plus'
  import pdf from '@/assets/image/pdf.png'
  import { phone, verifyPhone } from '@/utils/validate'
  import _ from 'lodash'
  import { orderAnnexUpload, orderVideoUpload } from '@/api/upload'
  import {
    empSave,
    getNetworkDetailEmpListDetail,
    getNetworkEmpLevelSelect,
    getNetworkEmpSkillSelect,
    getNetworkPageSelect,
    networkEmpFieldSelect,
  } from '@/api/network'
  import { Film, UploadFilled } from '@element-plus/icons-vue'
  import video from '@/assets/image/pages/order/new/video.png'
  import { CustomFieldRender, CustomFieldRenderArr } from './types'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import { useGetAccountInfoByPhone } from '@/services/pages/network/detail'
  import { useIsEmpJoinNetwork } from '@/services/pages/network/useNetwork'

  const { accountInfoByPhone, getAccountInfoLoading, getAccountInfo } = useGetAccountInfoByPhone()
  const {
    isEmpJoinNetwork,
    judgeLoading: judgeEmpIsJoinNetworkLoading,
    judge: judgeEmpIsJoinNetwork,
  } = useIsEmpJoinNetwork()

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    networkId: {
      type: String,
      required: true,
    },
    emp: String,
    getRow: {
      type: Object as PropType<NetworkAPIResponse.NetworkPersonListItem>,
      default: () => null,
    },
    isAdd: {
      type: Boolean,
      default: () => true,
    },
    teamType: [String, Number],
  })
  const { networkId, getRow, isAdd, teamType } = toRefs(props)
  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update-list'): void
  }>()

  const loading = ref(false)
  const onsaveloading = ref(false)
  const empRelationId = ref()
  const formRef = ref()
  var right_type = [
    'avi',
    'wmv',
    'mpg',
    'mpeg',
    'mov',
    'rm',
    'ram',
    'swf',
    'flv',
    'mp4',
    'wma',
    'rm',
    'rmvb',
    'flv',
    'mpg',
    'mkv',
  ]
  let networkEmpVo = ref({
    accountId: null, //账号ID
    accountUserName: '', //	登录用户名
    accountUserPhone: '', //登录手机号
    delNetworkIds: [], //	删除的网点ID
    enableStore: false,
    fieldVals: [
      // {
      //     "fieldId": null,
      //     "id": null,
      //     "name": "",
      //     "type": null,
      //     "value": ""
      // }
    ],
    id: null,
    networkId: '', //网点ID
    quit: false, //	在职状态：false-在职，true-离职
    superManager: false, //管理权限：false-普通管理员，true-超级管理员
    autoSureReceiveOrder: true, //工程师自动接单策略：false-手动确认，true-自动确认,示例值(true)
    networkEmpLevelId: null, //等级ID
    networkEmpSkillIds: [], //工程师技能ID
    number: null,
  })
  const rulesForm = ref({
    accountUserName: [{ required: true, message: '请输入姓名', trigger: ['blur', 'change'] }],
    moduleIds: [{ required: true, message: '适用模块', trigger: ['blur', 'change'] }],
    remindMode: [{ required: true, message: '提醒方式', trigger: ['blur', 'change'] }],
    dateType: [{ required: true, message: '生效时间', trigger: ['blur', 'change'] }],
    accountUserPhone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: phone(networkEmpVo.value.accountUserPhone), trigger: 'blur' },
    ],
  })

  // 获取人员详情加载状态
  const getNetworkDetailEmpListDetailLoading = ref(false)

  /**
   * 查询账号信息
   * @param {string} phone - 手机号
   */
  const findBtn = async (phone: string) => {
    if (!verifyPhone(phone)) {
      return
    }
    // if (networkId.value && !networkEmpVo.value.id) {
    //   await judgeEmpIsJoinNetwork(phone)
    //   if (isEmpJoinNetwork.value) {
    //     HMessageBox.error(infoTip.network.detail.empIsJoinedNetwork)
    //     return false
    //   }
    // }
    await getAccountInfo(phone, props.networkId)
    if (accountInfoByPhone.value.networkEmpId) {
      await editDialogShow(false, {
        empRealtionId: accountInfoByPhone.value.networkEmpRelationId || '0',
        id: accountInfoByPhone.value.networkEmpId,
      })
      HMessage.success(infoTip.network.create.getAccountSuccess)
      return
    }

    if (!accountInfoByPhone.value.id) {
      HMessageBox.warning(infoTip.network.create.phoneNotRegister)
    }
    Object.assign(networkEmpVo.value, {
      networkEmpLevelId: null,
      accountUserName: accountInfoByPhone.value.name,
      networkEmpSkillIds: [],
      quit: false,
      superManager: false,
      autoSureReceiveOrder: true,
      enableStore: false,
      fieldVals: [],
      accountId: null,
      delNetworkIds: [],
      networkId: networkId.value,
      number: null,
    })
    selfDefined()
    getNetworkEmpLevelSelectList('')
    getNetworkEmpSkillSelectlist('')
    getNetworkPageSelectList('')
  }

  // 添加or修改员工信息
  async function editDialogShow(add: boolean, val: any = null) {
    if (!add) {
      empRelationId.value = val.empRealtionId
      getNetworkDetailEmpListDetailLoading.value = true
      const res = await getNetworkDetailEmpListDetail(val.empRealtionId, val.id)
      getNetworkDetailEmpListDetailLoading.value = false
      if (res.data.success) {
        networkEmpVo.value = { ...networkEmpVo.value, ...res.data.data.row }
        if (props.getRow && props.getRow.id) {
          networkEmpVo.value.id = props.getRow.id
        }
        if (networkEmpVo.value.networkEmpLevelId === '0') {
          networkEmpVo.value.networkEmpLevelId = ''
        }
        if (networkEmpVo.value.superManager === null) {
          networkEmpVo.value.superManager = false
        }
        if (networkEmpVo.value.quit === null) {
          networkEmpVo.value.quit = false
        }
        // 获取自定义字段
        networkEmpFieldSelect().then((res2) => {
          networkEmpVo.value.fieldVals = res2.data.data.rows.map((item) => {
            item['fieldId'] = item.id
            item.id = null
            return item
          })
          networkEmpVo.value.fieldVals = networkEmpVo.value.fieldVals.map((o) => {
            if (o.type == 5 || o.type == 6 || o.type == 7) {
              o.value = []
              o.imgarr = []
            } else if (o.type == 4) {
              o.value = []
            } else {
              o.value = ''
            }
            res.data.data.row.fieldVals.map((item) => {
              if (o.fieldId == item.fieldId) {
                o.id = item.id
                if (item.type == 5 || item.type == 6 || item.type == 7) {
                  let ov = item.optVos.map((vo) => {
                    return { id: vo.id, image: vo.optValue }
                  })
                  o.imgarr = [...ov]
                } else if (item.type == 4) {
                  let ov = item.optVos.map((vo) => vo.optValue)
                  o.value = [...ov]
                } else {
                  o.value = item.optVos.map((vo) => vo.optValue)[0]
                }
              }
            })
            return o
          })
          networkEmpVo.value.fieldVals = networkEmpVo.value.fieldVals.sort(
            (firstItem, secondItem) => firstItem.type - secondItem.type,
          )
          setCustomFieldRender()
        })
        networkEmpVo.value.networkId = props.networkId ? props.networkId : ''
        networkEmpVo.value.networkEmpLevelId =
          networkEmpVo.value.networkEmpLevelId == 0 ? null : networkEmpVo.value.networkEmpLevelId
      } else {
        HMessageBox.error(res.data.message)
      }
    } else {
      networkEmpVo.value = {
        accountId: null,
        accountUserName: '',
        accountUserPhone: '',
        delNetworkIds: [],
        fieldVals: [],
        id: null,
        networkId: networkId.value,
        enableStore: false,
        quit: false,
        superManager: false,
        autoSureReceiveOrder: true,
        networkEmpLevelId: null, //等级ID
        networkEmpSkillIds: [], //工程师技能ID
      }
      selfDefined()
    }
    getNetworkEmpLevelSelectList('')
    getNetworkEmpSkillSelectlist('')
    getNetworkPageSelectList('')
  }

  // 保存加载
  const saveLoading = ref(false)

  // 保存
  async function onSave() {
    if (!verifyPhone(networkEmpVo.value.accountUserPhone)) {
      return
    }
    // if (networkId.value && !networkEmpVo.value.id) {
    //   await judgeEmpIsJoinNetwork(networkEmpVo.value.accountUserPhone)
    //   if (isEmpJoinNetwork.value) {
    //     HMessageBox.error(infoTip.network.detail.empIsJoinedNetwork)
    //     return false
    //   }
    // }
    if (!formRef.value) return
    formRef.value.validate(async (val) => {
      if (val) {
        saveLoading.value = true
        let dataSave = _.cloneDeep(networkEmpVo.value)
        // 判断是否有自定义字段文件上传
        if (dataSave.fieldVals.length > 0) {
          for (const key in dataSave.fieldVals) {
            let item = dataSave.fieldVals[key]
            if (item.type == 5 || item.type == 6 || item.type == 7) {
              let img = [] //新上传的
              let isImg = [] //已经上传的
              for (const i in item.imgarr) {
                const it = item.imgarr[i]
                if (it.file) {
                  img.push(it.file)
                } else {
                  isImg.push(it)
                }
              }
              if (img.length > 0) {
                if (item.type == 7) {
                  const res = await orderVideoUpload(img)
                  if (res.data.success) {
                    for (let i = 0; i < res.data.data.rows.length; i++) {
                      item.value.push({ id: null, image: res.data.data.rows[i] })
                    }
                  } else {
                    ElMessage({
                      message: res.data.message,
                      type: 'error',
                      duration: 5000,
                      plain: true,
                      showClose: true,
                    })
                  }
                } else {
                  const res = await orderAnnexUpload(img)
                  if (res.data.success) {
                    for (let i = 0; i < res.data.data.rows.length; i++) {
                      item.value.push({ id: null, image: res.data.data.rows[i] })
                    }
                  } else {
                    ElMessage({
                      message: res.data.message,
                      type: 'error',
                      duration: 5000,
                      plain: true,
                      showClose: true,
                    })
                  }
                }
              }
              item.value = [...isImg, ...item.value]
              if (item.type == 5 || item.type == 6 || item.type == 7) {
                item.value = item.value
              }
            }
          }
        }
        dataSave.fieldVals = dataSave.fieldVals.map((item) => {
          let tem = []
          if (item.type === 5 || item.type === 6 || item.type === 7) {
            tem = item.value.map((o) => {
              return { id: o.id, optValue: o.image }
            })
          } else if (item.type === 4) {
            tem = item.value.map((o) => {
              return { id: null, optValue: o }
            })
          } else {
            tem = [{ id: null, optValue: item.value }]
          }
          return { ...item, optVos: tem }
        })
        loading.value = true
        const res = await empSave(dataSave)
        if (res.data.success) {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
          })
          emits('update-list') //更新列表
          onCancel()
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
        loading.value = false
        saveLoading.value = false
      } else {
        ElMessage({
          showClose: true,
          message: '请填写完整信息！',
          type: 'warning',
          duration: 5000,
          plain: true,
        })
      }
    })
  }

  /**
   * 自定义字段渲染结构，用于方便控制样式
   */
  const customFieldRender = ref<CustomFieldRender>({
    txtSelect: [],
    uploadFile: [],
    radioCheckboxRate: [],
    textarea: [],
  })
  const setCustomFieldRender = () => {
    customFieldRender.value.radioCheckboxRate = []
    customFieldRender.value.uploadFile = []
    customFieldRender.value.txtSelect = []
    customFieldRender.value.textarea = []
    networkEmpVo.value.fieldVals.forEach((field, fieldIndex) => {
      if ([5, 6, 7].includes(field.type)) {
        customFieldRender.value.uploadFile.push({
          showLabelTooltip: false,
          sourceArrIndex: fieldIndex,
          name: field.name,
          type: field.type,
          formItemProp: `fieldVals[${fieldIndex}][imgarr]`,
          rules: [
            {
              required: field.required,
              message: field.tip || '请选择文件',
              trigger: ['change', 'blur'],
            },
          ],
          tip: field.tip || '请选择文件',
          contents: field.contents,
          uploadQty: field.uploadQty,
          uploadSize: field.uploadSize,
        })
      }
      if (field.type === 1 || ([3, 4].includes(field.type) && field.contents?.length > 3)) {
        customFieldRender.value.txtSelect.push({
          showLabelTooltip: false,
          sourceArrIndex: fieldIndex,
          name: field.name,
          type: field.type,
          formItemProp: `fieldVals[${fieldIndex}][value]`,
          rules: [
            {
              required: field.required,
              message: field.tip || (field.type === 1 ? '请输入' : '请选择'),
              trigger: ['change', 'blur'],
            },
          ],
          tip: field.tip || (field.type === 1 ? '请输入' : '请选择'),
          contents: field.contents,
        })
      }
      if (field.type === 8 || ([3, 4].includes(field.type) && field.contents?.length <= 3)) {
        customFieldRender.value.radioCheckboxRate.push({
          showLabelTooltip: false,
          sourceArrIndex: fieldIndex,
          name: field.name,
          type: field.type,
          formItemProp: `fieldVals[${fieldIndex}][value]`,
          rules: [
            {
              required: field.required,
              message: field.tip || '请选择',
              trigger: ['change', 'blur'],
            },
          ],
          tip: field.tip || '请选择',
          contents: field.contents,
        })
      }
      if (field.type === 2) {
        customFieldRender.value.textarea.push({
          showLabelTooltip: false,
          sourceArrIndex: fieldIndex,
          name: field.name,
          type: field.type,
          formItemProp: `fieldVals[${fieldIndex}][value]`,
          rules: [
            {
              required: field.required,
              message: field.tip || '请输入',
              trigger: ['change', 'blur'],
            },
          ],
          tip: field.tip || '请输入',
          contents: field.contents,
        })
      }
    })
  }

  // 获取自定义字段
  const selfDefined = async () => {
    await networkEmpFieldSelect().then((res) => {
      if (res.data.data.rows.length > 0) {
        networkEmpVo.value.fieldVals = res.data.data.rows.map((o) => {
          o.fieldId = o.id
          o.id = null
          if (o.type == 5 || o.type == 6 || o.type == 7) {
            o.value = []
            o.imgarr = []
          } else if (o.type == 4) {
            o.value = []
          } else {
            o.value = ''
          }
          return o
        })
        networkEmpVo.value.fieldVals = networkEmpVo.value.fieldVals.sort(
          (firstItem, secondItem) => firstItem.type - secondItem.type,
        )
        setCustomFieldRender()
      }
    })
  }
  // 添加图片
  const handleChange2 = (uploadFile: UploadFile, field: CustomFieldRenderArr) => {
    if (field.uploadSize < uploadFile.size / 1024 / 1024) {
      onExceedSize(field)
      return
    }
    if (networkEmpVo.value.fieldVals[field.sourceArrIndex].imgarr.length >= field.uploadQty) {
      onExceedNub(field)
      return
    }
    const { uid, name } = uploadFile.raw
    const tmp = {
      uid,
      name,
      image: window.URL.createObjectURL(uploadFile.raw),
      file: uploadFile.raw,
    }
    networkEmpVo.value.fieldVals[field.sourceArrIndex].imgarr.push(tmp)
  }
  const onExceedSize = _.debounce((item) => {
    ElMessage({
      showClose: true,
      message:
        item.type == 5
          ? '图片'
          : item.type == 6
          ? '附件'
          : '视频' + '大小不能超过' + item.uploadSize + 'MB!',
      type: 'error',
      duration: 5000,
      plain: true,
    })
  }, 10)
  const onExceedNub = _.debounce((item) => {
    ElMessage({
      showClose: true,
      message: `${item.type == 5 ? '图片' : item.type == 6 ? '附件' : '视频'} 数量不能超过 ${
        item.uploadQty
      }!`,
      type: 'error',
      duration: 5000,
      plain: true,
    })
  }, 10)
  // 删除图片
  const deleteItem2 = (bigindex, index) => {
    networkEmpVo.value.fieldVals = networkEmpVo.value.fieldVals.map((arr, j) => {
      if ((arr.type == 5 || arr.type == 6 || arr.type == 7) && j == bigindex) {
        arr.imgarr = arr.imgarr.filter((o, i) => i != index)
      }
      return arr
    })
  }
  // 查看图片
  const isPdf = ref()
  const file = ref(null)
  const dialogContract = ref(false)
  const lookFile = (val, tem) => {
    file.value = val
    dialogContract.value = true
    isPdf.value = tem
  }

  // 获取工程师等级
  const networkEmpLevelList = ref([])
  const getNetworkEmpLevelSelectList = async (val) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    let res = await getNetworkEmpLevelSelect(data)
    networkEmpLevelList.value = res.data.data.rows
  }
  const searchKey = ref('')
  const getNetworkEmpPageSelectList = (val) => {
    searchKey.value = val
  }

  // 获取工程师技能
  const networkEmpSkillList = ref([])
  const getNetworkEmpSkillSelectlist = async (val) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    let res = await getNetworkEmpSkillSelect(data)
    networkEmpSkillList.value = res.data.data.rows
  }
  const searchSkill = ref('')
  const getNetworkSkillPageSelectList = (val) => {
    searchSkill.value = val
  }

  //获取网点下拉
  const networks = ref([])
  const getNetworkPageSelectList = (val) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    getNetworkPageSelect(data).then((res) => {
      if (res.data.success) {
        networks.value = res.data.data.rows
      }
    })
  }
  const searchNetworks = ref('')

  const visible = ref(false)

  const onCancel = () => {
    formRef.value.resetFields()
    visible.value = false
    emits('update:modelValue', visible.value)
  }

  //监听查看附件弹窗关闭时销毁 iframe内存
  watch(dialogContract, (n) => {
    if (!n) {
      file.value = 'about:blank'
    }
  })

  watch(searchKey, (n) => {
    getNetworkEmpLevelSelectList(n)
  })

  watch(searchSkill, (n) => {
    getNetworkEmpSkillSelectlist(n)
  })

  watch(searchNetworks, (n) => {
    getNetworkPageSelectList(n)
  })

  watch(
    props,
    (value) => {
      visible.value = value.modelValue
      if (visible.value) {
        editDialogShow(isAdd.value, getRow.value)
      }
    },
    { immediate: true, deep: true },
  )
</script>

<style lang="scss" scoped>
  :deep(.el-input .el-input__wrapper) {
    height: 26px !important;
  }

  :deep(.el-select__tags) {
    max-height: 100px;
    overflow-y: auto;
  }

  @import './selfscss';
</style>
